package com.ruoyi.system.utils;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SmsUtils {

    private static final String  ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI5tBaQwwZHWU7eRWosvbW";
    private static final String  ALIBABA_CLOUD_ACCESS_KEY_SECRET = "cmI6fJhunbrflaL72qbKvM8GFKNohG";
    private static final String  SIGN_NAME = "阿里云短信测试";
    private static final String  TEMPLATE_CODE = "SMS_154950909";






    public  String sendMsg(String phone) throws Exception {
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(ALIBABA_CLOUD_ACCESS_KEY_ID)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(ALIBABA_CLOUD_ACCESS_KEY_SECRET);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = new Client(config);
        int randomNumber = (int) (Math.random() * 9000) + 1000;

        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(SIGN_NAME)
                .setTemplateCode(TEMPLATE_CODE)
                .setPhoneNumbers(phone)
                .setTemplateParam("{code:"+randomNumber+"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info(sendSmsResponse.body.message);
            return String.valueOf(randomNumber);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error(error.getMessage());
            log.error(error.getData().get("Recommend").toString());
            // 诊断地址
            com.aliyun.teautil.Common.assertAsString(error.message);
            throw new ServiceException("发送短信失败");
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error(error.getMessage());
            com.aliyun.teautil.Common.assertAsString(error.message);
            throw new ServiceException("发送短信失败");
        }
    }
}